import * as fs from 'fs';
import * as path from 'path';
import { fileTypeFromBuffer } from 'file-type';

type FileHandler = {
  process: (buffer: Buffer) => Promise<Buffer>;
  supportedTypes: string[];
};

export class FileCompatibility {
  private handlers: Map<string, FileHandler> = new Map();

  constructor() {
    this.registerDefaultHandlers();
  }

  private registerDefaultHandlers() {
    // 图片处理器
    this.registerHandler({
      process: this.processImage,
      supportedTypes: ['image/png', 'image/jpeg', 'image/webp']
    });

    // 文档处理器
    this.registerHandler({
      process: this.processDocument,
      supportedTypes: ['application/pdf', 'text/plain']
    });
  }

  registerHandler(handler: FileHandler) {
    for (const type of handler.supportedTypes) {
      this.handlers.set(type, handler);
    }
  }

  async processFile(filePath: string): Promise<Buffer> {
    const buffer = await fs.promises.readFile(filePath);
    const type = await fileTypeFromBuffer(buffer);
    
    if (!type || !this.handlers.has(type.mime)) {
      throw new Error(`Unsupported file type: ${type?.mime || 'unknown'}`);
    }

    return this.handlers.get(type.mime)!.process(buffer);
  }

  private async processImage(buffer: Buffer): Promise<Buffer> {
    // 图片转换逻辑
    return buffer; // 示例实现
  }

  private async processDocument(buffer: Buffer): Promise<Buffer> {
    // 文本类型特殊处理
    try {
      const text = TextProcessor.normalizeText(buffer);
      const processed = TextProcessor.processLayout(text);
      return Buffer.from(processed, 'utf8');
    } catch (e) {
      // 二进制文档回退原始处理
      return buffer;
    }
  }

  private isTextFile(mime: string): boolean {
    return [
      'text/plain',
      'text/html',
      'application/json',
      'application/xml'
    ].includes(mime);
  }
}